//
//  LoginViewController.m
//  customer
//
//  Created by Holothurian on 2018/10/20.
//  Copyright © 2018年 yinlong. All rights reserved.
//

#import "LoginViewController.h"
#import "MainTabBarController.h"
#import "RegisterViewController.h"
#import "FindPasswordViewController.h"
#import "BindingPhoneNumViewController.h"

static NSString* const kWXAuthDenyTitle = @"授权失败";
static NSString* const kWXLoginErrorTitle = @"微信登录失败";

typedef void(^LoginSuccess)(void);

@interface LoginViewController ()<WXAuthDelegate>

@property (nonatomic,strong)UITextField * phoneTF;

@property (nonatomic,strong)UITextField * passWordTF;

@property (nonatomic,strong)UIButton * loginButton;

@property (nonatomic,copy)LoginSuccess loginSuccess;

@property (nonatomic,strong)UIView *layerView;
@end

@implementation LoginViewController

- (instancetype)initWithLoginSuccess:(void (^)(void))success{
    if (self = [super init]) {
        self.loginSuccess = success;
        return self;
    }
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self layoutUI];
}




- (void)layoutUI{
    self.title = @"登录";
    AutoWeakSelf
    UIView * backView = [UIView new];
    backView.userInteractionEnabled = YES;
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    UIImageView * logoImageView = [UIImageView new];
    logoImageView.image = [UIImage imageNamed:@"ssehLogo"];
    [backView addSubview:logoImageView];
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(backView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(90, 90));
        make.top.equalTo(backView.mas_top).offset((50+NAVIGATION_BAR_HEIGHT)*PROPORTION_HEIGHT_IPHONE6);
    }];
    logoImageView.layer.cornerRadius = 10;
    logoImageView.layer.masksToBounds = YES;
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.text = @"一步e家";
    nameLabel.textColor = RGBColor(51, 51,51);
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = Font(20);
    [backView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(backView.mas_centerX);
        make.top.equalTo(logoImageView.mas_bottom).offset(0);
        make.size.mas_equalTo(CGSizeMake(86, 33));
    }];
    
    //手机号
    UIView * phoneView = [UIView new];
    phoneView.layer.borderColor = RGBColor(48, 48, 48).CGColor;
    phoneView.layer.borderWidth = 1.0f;
    phoneView.layer.cornerRadius = 15;
    phoneView.layer.masksToBounds = YES;
    [backView addSubview:phoneView];
    [phoneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameLabel.mas_bottom).offset(40*PROPORTION_HEIGHT_IPHONE6);
        make.left.equalTo(backView).offset(35*PROPORTION_WIDTH_IPHONE6);
        make.right.equalTo(backView).offset(-35*PROPORTION_WIDTH_IPHONE6);
        make.height.mas_equalTo(40);
    }];
    
    self.phoneTF = [UITextField new];
    self.phoneTF.placeholder = @"请输入您的手机号码";
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.phoneTF.textColor = [UIColor blackColor];
    self.phoneTF.font = Font(16);
    [self.phoneTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [phoneView addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(phoneView.mas_left).offset(30*PROPORTION_WIDTH_IPHONE6);
        make.right.top.bottom.equalTo(phoneView);
    }];
    
    //密码
    UIView * passwordView = [UIView new];
    passwordView.layer.borderColor = RGBColor(48, 48, 48).CGColor;
    passwordView.layer.borderWidth = 1.0f;
    passwordView.layer.cornerRadius = 15;
    [backView addSubview:passwordView];
    [passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(phoneView.mas_bottom).offset(15*PROPORTION_HEIGHT_IPHONE6);
        make.left.right.height.equalTo(phoneView);
    }];
    
    self.passWordTF = [UITextField new];
    self.passWordTF.placeholder = @"请输入您的密码";
    self.passWordTF.secureTextEntry = YES;
    self.passWordTF.textColor = [UIColor blackColor];
    self.passWordTF.font = Font(16);
    [self.passWordTF setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
    [passwordView addSubview:self.passWordTF];
    [self.passWordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordView.mas_left).offset(30*PROPORTION_WIDTH_IPHONE6);
        make.right.top.bottom.equalTo(passwordView);
    }];
    
    //立即登录
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.loginButton.titleLabel.font = Font(16);
    self.loginButton.layer.cornerRadius = 10;
    [self.loginButton setBackgroundColor:RGBColor(51, 51, 51)];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginButton addTarget:self action:@selector(logInButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:self.loginButton];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordView.mas_bottom).offset(40*PROPORTION_HEIGHT_IPHONE6);
        make.left.equalTo(backView).offset(15*PROPORTION_WIDTH_IPHONE6);
        make.right.equalTo(backView).offset(-15*PROPORTION_WIDTH_IPHONE6);
        make.height.mas_equalTo(47);
    }];
    
    //忘记密码  立即注册
    UIView * lineView = [UIView new];
    lineView.backgroundColor = RGBColor(219, 219, 219);
    [backView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(backView);
        make.top.equalTo(weakSelf.loginButton.mas_bottom).offset(10*PROPORTION_HEIGHT_IPHONE6);
        make.width.equalTo(weakSelf.loginButton);
        make.height.mas_equalTo(1);
    }];
    
    UIButton * findPWButton = [UIButton buttonWithType:UIButtonTypeCustom];
    findPWButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [findPWButton setTitle:@"忘记密码" forState:UIControlStateNormal];
    [findPWButton setTitleColor:RGBColor(0, 0, 0) forState:UIControlStateNormal];
    [findPWButton addTarget:self action:@selector(findPWButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:findPWButton];
    [findPWButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(lineView);
        make.top.equalTo(lineView.mas_bottom).offset(10*PROPORTION_HEIGHT_IPHONE6);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    UIButton * registButton = [UIButton buttonWithType:UIButtonTypeCustom];
    registButton.titleLabel.font = Font(14);
    [registButton setTitle:@"立即注册" forState:UIControlStateNormal];
    [registButton setTitleColor:[UIColor roseRed] forState:UIControlStateNormal];
    [registButton addTarget:self action:@selector(registButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:registButton];
    [registButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(lineView);
        make.top.equalTo(lineView.mas_bottom).offset(10*PROPORTION_HEIGHT_IPHONE6);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = [UIColor whiteColor];
    [backView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(backView).offset(-bottomPadding(10) *PROPORTION_HEIGHT_IPHONE6);
        make.left.right.equalTo(lineView);
        make.height.mas_equalTo(80 * PROPORTION_HEIGHT_IPHONE6);
    }];
    
    UIView *leftLine = [[UIView alloc]init];
    leftLine.backgroundColor = [HSPublic colorWithHexString:@"#333333"];
    [bottomView addSubview:leftLine];
    [leftLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomView);
        make.top.equalTo(bottomView).offset(10 * PROPORTION_HEIGHT_IPHONE6);
        make.size.mas_equalTo(CGSizeMake(F_DEVICE_W/2.0 - 35 * PROPORTION_WIDTH_IPHONE6, 1));
    }];
    UIView *rightLine = [[UIView alloc]init];
    rightLine.backgroundColor = [HSPublic colorWithHexString:@"#333333"];
    [bottomView addSubview:rightLine];
    [rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView);
        make.top.equalTo(bottomView).offset(10 * PROPORTION_HEIGHT_IPHONE6);
        make.size.mas_equalTo(CGSizeMake(F_DEVICE_W/2.0 - 35 * PROPORTION_WIDTH_IPHONE6, 1));
    }];
    
    UILabel *orLabel = [[UILabel alloc]init];
    orLabel.text = @"OR";
    orLabel.textColor = [HSPublic colorWithHexString:@"333333"];
    orLabel.font = Font30;
    orLabel.textAlignment = NSTextAlignmentCenter;
    [bottomView addSubview:orLabel];
    [orLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomView);
        make.left.equalTo(leftLine.mas_right).offset(0);
        make.right.equalTo(rightLine.mas_left).offset(0);
        make.height.mas_equalTo(20 * PROPORTION_HEIGHT_IPHONE6);
    }];
    UIImageView *wxImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"wxIconImage"]];
    wxImgView.contentMode = UIViewContentModeScaleAspectFit;
    wxImgView.userInteractionEnabled = YES;
    [bottomView addSubview:wxImgView];
    [wxImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView);
        make.top.equalTo(orLabel.mas_bottom).offset(10 * PROPORTION_HEIGHT_IPHONE6);
        make.size.mas_equalTo(CGSizeMake(40 * PROPORTION_HEIGHT_IPHONE6, 40 * PROPORTION_HEIGHT_IPHONE6));
    }];
    self.layerView = [[UIView alloc]init];
    self.layerView.backgroundColor = [HSPublic colorWithHexString:@"666666" alpha:0.3];
    self.layerView.hidden = YES;
    self.layerView.userInteractionEnabled = NO;
    [backView addSubview:self.layerView];
    [self.layerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(wxImgView);
    }];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [wxImgView addGestureRecognizer:tap];
}

- (void)tapAction{
    //微信openid
    NSString  *openId = K_UserDefault_Read(Customer_WXAppOpen_id)?:@"";
    if (k_Is_Empty(openId)) {
        [[WXApiManager sharedManager]sendAuthRequestWithController:self delegate:self];
    }else{
        self.layerView.hidden = NO;
        [self wxCustomerLogin:openId];
    }
    
}

- (void)wxCustomerLogin:(NSString *)openid{
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kWXAppLoginMember parameters:@{@"weixin_app_open_id":openid?:@""} andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            MemberInfoManager *infoManager = [MemberInfoManager yy_modelWithDictionary:responseObject[@"data"]];
            if([infoManager.member_id integerValue]){
                //用户账号
                NSString * member_account = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_account"]];
                K_UserDefault_Write([NSString emptyStr:member_account], CustomerUserAccount);
                //用户id
                NSString * member_id = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_id"]];
                K_UserDefault_Write([NSString emptyStr:member_id], CustomerUserID);
                
                //token
                NSString * member_token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_token"]];
                K_UserDefault_Write([NSString emptyStr:member_token], CustomerUserToken);
                
                //用户真实姓名
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_real_name"]], Customer_member_real_name);
                
                //用户手机号
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_phone"]], Customer_member_phone);
                
                //订单量
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"order_count"]], Customer_order_count);
                
                //用户头像
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_img"]], Customer_member_img);
                
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"weixin_app_open_id"]], Customer_WXAppOpen_id);
                if (weakSelf.loginSuccess) {
                    weakSelf.loginSuccess();
                }
            }else{
                [weakSelf hideLoading];
                [weakSelf showErrorTipWithTitle:@"微信登陆失败"];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

#pragma mark - 登录 找回密码 注册
- (void)logInButtonClick:(UIButton *)button{
    
    if (self.phoneTF.text.length != 11 ) {
        [self showErrorTipWithTitle:@"手机号码输入错误"];
        return;
    }
    if (k_Is_Empty(self.passWordTF.text)) {
        [self showErrorTipWithTitle:@"请输入您的密码"];
        return;
    }
    [self showLoading];
    //获取Token、也即registrationID
    NSString *push_ID = K_UserDefault_Read(JPush_ID)?:@"";
    NSDictionary * par = @{@"member_account":self.phoneTF.text,@"member_password":self.passWordTF.text,@"member_type":@"1",@"jpush_id":push_ID};
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kLoginMember parameters:par andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            [weakSelf showSuccessWithType:0 AndTitle:@"登录成功"];
            //用户账号
            NSString * member_account = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_account"]];
            K_UserDefault_Write([NSString emptyStr:member_account], CustomerUserAccount);
            //用户id
            NSString * member_id = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_id"]];
            K_UserDefault_Write([NSString emptyStr:member_id], CustomerUserID);
            
            //token
            NSString * member_token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_token"]];
            K_UserDefault_Write([NSString emptyStr:member_token], CustomerUserToken);
            
            //用户真实姓名
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_real_name"]], Customer_member_real_name);
            
            //用户手机号
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_phone"]], Customer_member_phone);
            
            //订单量
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"order_count"]], Customer_order_count);
            
            //用户头像
            K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_img"]], Customer_member_img);
            if (weakSelf.loginSuccess) {
                weakSelf.loginSuccess();
            }
        }
        
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
    
}


- (void)findPWButtonClick:(UIButton *)button{
    
    FindPasswordViewController * vc = [[FindPasswordViewController alloc]init];
    vc.phoneStr = self.phoneTF.text?:@"";
    vc.isPush = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)registButtonClick:(UIButton *)button{
    
    RegisterViewController * vc = [[RegisterViewController alloc]init];
    vc.phoneStr = self.phoneTF.text?:@"";
    vc.isPush = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - WXAuthDelegate
- (void)wxAuthSucceed:(NSString *)code {
    [self showLoading];
    [[QYNetManager sharedManager]GET:WXSnsOauth2_Authorization_Code parameters:@{@"appid":WXOpenID,@"secret":WXAppSecret,@"code":code,@"grant_type":@"authorization_code"} SuccessBlock:^(id responseObject) {
        NSLog(@" authorization_code: %@",responseObject);
        [self hideLoading];
        if (responseObject) {
            WXAuthorizationCode *codeModel = [WXAuthorizationCode yy_modelWithDictionary:responseObject];
            [self requestUserInfoByAuthorizationCode:codeModel];
        }
    } Failure:^(NSError *error) {
        NSLog(@"%@",error);
        if (error) {
            [self hideLoading];
            [self showErrorTipWithTitle:error.localizedDescription];
        }
    }];
}

- (void)requestUserInfoByAuthorizationCode:(WXAuthorizationCode *)authCode{
    AutoWeakSelf
    [[QYNetManager sharedManager]GET:WXSnsUserInfo parameters:@{@"access_token":authCode.access_token,@"openid":authCode.openid} SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        NSLog(@"WXUserInfo:  %@",responseObject);
        if ([responseObject[@"errcode"] integerValue] == 40001) {
            [weakSelf wxRefreshToken:authCode];
        }else{
            NSDictionary *dict = responseObject;
            WXUserModel *userModel = [WXUserModel yy_modelWithDictionary:dict];
            [weakSelf wxLoginMemberWithOpenID:userModel];
        }
    } Failure:^(NSError *error) {
        if (error) {
            [weakSelf hideLoading];
            [weakSelf showErrorTipWithTitle:error.localizedDescription];
        }
    }];
}

- (void)wxRefreshToken:(WXAuthorizationCode *)authCode{
    static NSInteger count;
    AutoWeakSelf
    [[QYNetManager sharedManager]GET:WXSnsRefreshToken parameters:@{@"appid":WXOpenID,@"grant_type":@"refresh_token",@"refresh_token":authCode.refresh_token} SuccessBlock:^(id response) {
        NSLog(@"%@",response);
        [weakSelf hideLoading];
        if (response[@"access_token"]) {
            WXAuthorizationCode *refreshCode = [WXAuthorizationCode yy_modelWithDictionary:response];
            if (count == 3) {
                [weakSelf showErrorTipWithTitle:@"微信绑定失败"];
            }else{
                [weakSelf requestUserInfoByAuthorizationCode:refreshCode];
                count++;
            }
        }else{
            [weakSelf showErrorTipWithTitle:response[@"errmsg"]];
        }
    } Failure:^(NSError *error) {
        if (error) {
            [weakSelf hideLoading];
            [weakSelf showErrorTipWithTitle:error.localizedDescription];
        }
    }];
}

- (void)wxLoginMemberWithOpenID:(WXUserModel *)userModel{
    AutoWeakSelf
    [[QYNetManager sharedManager]POST:kWXAppLoginMember parameters:@{@"weixin_app_open_id":userModel.openid?:@""} andApiTyp:CustomerApiTypMain SuccessBlock:^(id responseObject) {
        [weakSelf hideLoading];
        if ([responseObject[@"status"] isEqualToString:@"error"]) {
            [weakSelf showErrorTipWithTitle:responseObject[@"error"]];
        }else{
            MemberInfoManager *infoManager = [MemberInfoManager yy_modelWithDictionary:responseObject[@"data"]];
            if ([infoManager.member_id  integerValue]==0) {
                infoManager.member_nick_name = userModel.nickname?:@"";
                infoManager.member_img = userModel.headimgurl?:@"";
                infoManager.weixin_open_id = userModel.openid?:@"";
                if ([userModel.sex isEqualToString:@"1"]) {
                    infoManager.member_sex = @"m";
                    infoManager.member_sex_show = @"男";
                }else{
                    infoManager.member_sex = @"w";
                    infoManager.member_sex_show = @"女";
                }
                infoManager.union_id = userModel.unionid?:@"";
                BindingPhoneNumViewController *bindVC = [[BindingPhoneNumViewController alloc]init];
                bindVC.infoManger = infoManager;
                TAB_PUSH(weakSelf, bindVC, YES);
            }else if([infoManager.member_id integerValue]){
                //用户账号
                NSString * member_account = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_account"]];
                K_UserDefault_Write([NSString emptyStr:member_account], CustomerUserAccount);
                //用户id
                NSString * member_id = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_id"]];
                K_UserDefault_Write([NSString emptyStr:member_id], CustomerUserID);
                
                //token
                NSString * member_token = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"member_token"]];
                K_UserDefault_Write([NSString emptyStr:member_token], CustomerUserToken);
                
                //用户真实姓名
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_real_name"]], Customer_member_real_name);
                
                //用户手机号
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_phone"]], Customer_member_phone);
                
                //订单量
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"order_count"]], Customer_order_count);
                
                //用户头像
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"member_img"]], Customer_member_img);
                
                K_UserDefault_Write([NSString emptyStr:responseObject[@"data"][@"weixin_app_open_id"]], Customer_WXAppOpen_id);
                
                if (weakSelf.loginSuccess) {
                    weakSelf.loginSuccess();
                }
                
            }else{
                [weakSelf hideLoading];
                [weakSelf showErrorTipWithTitle:@"微信绑定失败"];
            }
        }
    } Failure:^(NSError *error) {
        [weakSelf hideLoading];
        [weakSelf showErrorTipWithTitle:CustomerPoolNetStr];
    }];
}

- (void)wxAuthDenied {
    SHOW_ALERT(@"", kWXAuthDenyTitle, nil, @"确定", 88);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
